<template>
  <el-upload v-if="uploadType === 'drag'" class="upload-demo" drag action="" v-model:file-list="fileList"
    :http-request="handleUpload" :accept="accept" :on-change="handleChange" :before-upload="beforeUpload">
    <el-icon class="el-icon--upload"><upload-filled /></el-icon>
    <div class="el-upload__text"><em>点击上传文件</em></div>
    <template #tip>
      <div class="el-upload__tip">只能上传excel格式文件,其中包括 .xls .xlsx .csv</div>
    </template>
  </el-upload>
  <el-upload v-if="uploadType === 'button'" class="upload-demo" drag action="" v-model:file-list="fileList"
    :http-request="handleUpload" :accept="accept" :on-change="handleChange" :before-upload="beforeUpload">
    <ElButton :icon="UploadFilled">点击上传文件</ElButton>
  </el-upload>
</template>
<script lang="tsx" setup>
import { UploadFilled } from '@element-plus/icons-vue'
import { computed, reactive, ref } from 'vue';
import { SysfilesApi } from '@/api-services/apis/sysfiles-api';
import { feature, getAPI } from '@/axios-utils';
import { queryDone } from '@/utils/api';
import { ElMessage, UploadFile, UploadFiles, UploadProps, UploadRawFile, UploadRequestOptions, UploadStatus } from 'element-plus';

//组件开放给外部一个必填属性名为Category
const props = defineProps({
  /**
   * 文件分类
   */
  category: {
    type: String as () => string,
    required: true
  },
  fileMaxLength: {
    type: Number as () => number,
    //默认10MB
    default: 1024 * 1024 * 10
  },
  allowExtensions: {
    type: Array as () => string[],
    default: () => ['.jpg', '.jpeg', '.png', '.gif', '.pdf']
  },
  uploadType: {
    type: String as () => 'button' | 'drag',
    default: 'drag'
  },
  multiple: {
    type: Boolean as () => boolean,
    default: false
  },
  showUploadList: {
    type: Boolean as () => boolean,
    default: true
  }
});


const accept = computed(() => {
  return props.allowExtensions.join(',');
});
const fileList = ref<UploadProps['fileList']>([]);

const uploadAccept = computed(() => {
  let defaultExtensions = ['.jpg', '.jpeg', '.png', '.gif', '.pdf'];
  if (props.allowExtensions.length > 0) {
    defaultExtensions = props.allowExtensions as string[];
  }

  return defaultExtensions;
})
const beforeUpload = async (rawFile: UploadRawFile) => {
  if (!rawFile) {
    window.$message?.error('请选择文件');
    return false;
  }
  if (rawFile.size > props.fileMaxLength) {
    window.$message?.error('文件大小超出限制');
    return false;
  }
  //获取file.name的文件拓展名zifx
  const ext = rawFile.name.substring(rawFile.name.lastIndexOf('.'));
  if (!uploadAccept.value.includes(ext)) {
    window.$message?.error(`只能上传${uploadAccept.value.join(',')}格式的文件`);
    return false;
  }
}

interface Emits {
  (e: 'submitted', id: number): void;
}

const emit = defineEmits<Emits>();

const handleUpload = async (options: UploadRequestOptions) => {

  const file = options.file;
  //执行上传操作
  const [err, res] = await feature(getAPI(SysfilesApi)
    .uploadFormReturnIdForm(props.category, file));

  queryDone(err, async () => {
    const resState = res?.data?.data!;
    if (resState) {
      //上传成功
      options.onSuccess(res.data.data);
      //提交刷新
      emit('submitted', resState);
    }
  }, () => {
    const updateItem = setFileError(file.uid)
    if (updateItem) {
      if (err?.message) {
        window.$message?.error(err.message);
      } else if (updateItem.name) {
        window.$message?.error(`${updateItem.name} 上传失败`);
      }
    }
  });

};
//UploadStatus  ='ready' | 'uploading' | 'success' | 'fail'
const setFileError = (uid: number) => {
  const updateItem = fileList.value?.find(f => f.uid === uid);
  if (updateItem) {
    updateItem.status = 'fail';
  }
  return updateItem;
}
const handleChange = (uploadFile: UploadFile, uploadFiles: UploadFiles) => {


  console.log(uploadFile, uploadFiles)
  // if (status === 'done') {
  //   window.$message?.success(`${info.file.name} 上传成功`);
  // } else if (status === 'error') {
  //   window.$message?.error(`${info.file.name} 上传失败`);
  // }
};
function handleDrop(e: DragEvent) {
  console.log(e);
}

function init() {
  fileList.value = [];

}
defineExpose({
  init
})
</script>
<style lang="scss">
.upload-container {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;

  .upload-container-box {}
}
</style>
